package controller

import (
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"software/config"
	"software/model"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// 获取当前用户信息
func GetCurrentUser(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "未登录"})
		return
	}
	var user model.User
	if err := config.DB.First(&user, userID).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "用户不存在"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"success": true, "user": user})
}

// 更新当前用户信息（签名、头像）
func UpdateCurrentUser(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "未登录"})
		return
	}
	var req struct {
		Signature string `json:"signature"`
		Avatar    string `json:"avatar"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "参数错误"})
		return
	}
	var user model.User
	if err := config.DB.First(&user, userID).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "用户不存在"})
		return
	}
	user.Signature = req.Signature
	if req.Avatar != "" {
		user.Avatar = req.Avatar
	}
	if err := config.DB.Save(&user).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "保存失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"success": true, "user": user})
}

// 上传头像接口
func UploadAvatar(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "未登录"})
		return
	}
	file, err := c.FormFile("avatar")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "未选择文件"})
		return
	}
	// 保存路径
	dir := "uploads/avatar"
	_ = os.MkdirAll(dir, os.ModePerm)
	filename := time.Now().Format("20060102150405") + "_" + filepath.Base(file.Filename)
	path := filepath.Join(dir, filename)
	if err := c.SaveUploadedFile(file, path); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "保存失败"})
		return
	}
	// 生成可访问URL（假设静态资源映射到/uploads）
	avatarURL := "/uploads/avatar/" + filename
	// 更新用户头像
	var user model.User
	if err := config.DB.First(&user, userID).Error; err == nil {
		user.Avatar = avatarURL
		config.DB.Save(&user)
	}
	c.JSON(http.StatusOK, gin.H{"success": true, "url": avatarURL})
}

// 上传简历接口
func UploadResume(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "未登录"})
		return
	}
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "上传失败"})
		return
	}

	if filepath.Ext(file.Filename) != ".pdf" {
		c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "只允许上传PDF文件"})
		return
	}

	savePath := fmt.Sprintf("uploads/resumes/%d/%d_%s", userID, time.Now().Unix(), file.Filename)
	err = c.SaveUploadedFile(file, savePath)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "保存文件失败"})
		return
	}

	uid, ok := userID.(uint)
	if !ok {
		c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "用户ID类型错误"})
		return
	}
	resume := model.Resume{
		UserID:     uid,
		Filename:   file.Filename,
		URL:        "/" + savePath,
		UploadedAt: time.Now(),
		IsDefault:  false,
	}
	config.DB.Create(&resume)

	c.JSON(http.StatusOK, gin.H{"success": true, "url": resume.URL})
}

// 获取简历列表
func GetResumeList(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "未登录"})
		return
	}
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * pageSize

	var resumes []model.Resume
	var total int64

	config.DB.Model(&model.Resume{}).
		Where("user_id = ?", userID).
		Count(&total)

	config.DB.Where("user_id = ?", userID).
		Order("uploaded_at desc").
		Offset(offset).
		Limit(pageSize).
		Find(&resumes)

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"data": gin.H{
			"records": resumes,
			"total":   total,
		},
	})
}

// 删除简历
func DeleteResume(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "未登录"})
		return
	}
	id := c.Param("id")

	var resume model.Resume
	if err := config.DB.First(&resume, "id = ? AND user_id = ?", id, userID).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "简历不存在"})
		return
	}

	config.DB.Delete(&resume)
	c.JSON(http.StatusOK, gin.H{"success": true})
}

// 设置默认简历
func SetDefaultResume(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "未登录"})
		return
	}
	id := c.Param("id")

	// 清除用户原有默认简历
	config.DB.Model(&model.Resume{}).
		Where("user_id = ? AND is_default = ?", userID, true).
		Update("is_default", false)

	// 设置新默认
	result := config.DB.Model(&model.Resume{}).
		Where("id = ? AND user_id = ?", id, userID).
		Update("is_default", true)

	if result.RowsAffected == 0 {
		c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "简历不存在"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"success": true})
}
